<template>
  <div class="container">
    <el-tag
      v-for="(item, i) in tags"
      :key="i"
      closable
      :disable-transitions="true"
      @close="handleClose(i)"
      >{{ item }}</el-tag
    >
    <input
      class="input"
      :class="{ error: invalid }"
      placeholder="请输入"
      @keydown.enter="handleEnter"
      @blur="handleEnter"
      @input="invalid = false"
    />
    <el-icon v-show="showClear" style="cursor: pointer; color: #409eff" @click="handleClear"
      ><CircleClose
    /></el-icon>
  </div>
</template>

<script setup>
import { computed, ref } from 'vue';
import { ElTag, ElMessage, ElIcon } from 'element-plus';
import { CircleClose } from '@element-plus/icons-vue';

const tags = defineModel({ default: [], required: false, type: Array });

const showClear = computed(() => {
  return tags.value.length > 0;
});

function handleClear() {
  tags.value = [];
}

function handleClose(i) {
  tags.value.splice(i, 1);
}

const validList = ['aaa', 'bbb'];

async function request(input) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(input.split(';').filter((item) => item != '' && validList.includes(item)));
    }, 1000);
  });
}

function textToArray(text) {
  return text.split(';').filter((item) => item != '');
}
const invalid = ref(false);

function handleEnter(e) {
  console.log(e.target.value);
  request(e.target.value).then((res) => {
    const curList = textToArray(e.target.value);
    const invalidList = curList.filter((item) => !res.includes(item));
    const repeatList = tags.value.filter((item) => res.includes(item));
    if (repeatList.length > 0) {
      ElMessage.warning('已存在用户：' + repeatList.join(';'));
    }
    if (invalidList.length > 0) {
      invalid.value = true;
      e.target.value = invalidList.join(';');
      ElMessage.warning('请检查：' + e.target.value);
    } else {
      e.target.value = '';
    }
    tags.value = [...new Set(tags.value.concat(res))];
  });
}
</script>

<style scoped>
.container {
  height: 32px;
  display: flex;
  align-items: center;
  gap: 6px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  padding: 4px;
}

.container .input {
  flex-grow: 1;
  border: none;
  outline: none;
  padding: 0;
}

.input.error {
  color: red;
}
</style>
